<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use think\Request;
use app\admin\model\Manager;
use think\Session;

class Login extends Base
{
    /**
     * 渲染登录页面
     *
     * @return \think\Response
     */
    public function index()
    {
        $this -> alreadyLogin();
        return $this -> fetch();
    }

    /**
     * 验证用户信息
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function check(Request $request)
    {
        //设置状态
        $status = 0;

        // 获取表单数据
        $data = $request -> param();
        $username = $data['username'];
        $password = md5($data['password']);

        // 进行表数据查询
        $map = ['username' => $username];
        $manager = Manager::get($map);

        //查询结果校验
        if(is_null($manager)){
            $message = "用户名错误!";
        } elseif ($manager -> password != $password) {
            $message = "密码错误!";
        } else {
            $status = 200;
            $message = "验证成功!";
            
            // 更新用户数据
            $manager -> save(['lastTime' => time()]);
            
            // 保存session
            Session::set('userId', $manager['id']);
            Session::set('userInfo', $manager);

        }

        return ['status' => $status,'message'=>$message];
    }

    /**
     * 退出登录
     * 
     * @return \think\Response
     */
    public function logout(Request $request)
    {
        //删除用户session信息
        Session::delete('userId');
        Session::delete('userInfo');

        // 返回登录页面
        $this -> redirect('login/index');
    }
}
